﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Dokan;
using MirrorDrive.Operations;
using MirrorDrive.Server.Authorization;
using RemoteCode;

namespace MirrorDrive.Server
{
    public class MirrorServer
    {
        private NexumListener _listener;
        private SortedList<int, MirrorClient> _clients = new SortedList<int, MirrorClient>();
        private bool _stopped = false;

        internal AuthorizationBase _authorizationBase;

        public MirrorServer(ushort port, byte[] key, AuthorizationBase authorization)
        {
            if (authorization == null)
                throw new ArgumentNullException("authorization");

            _authorizationBase = authorization;
            _listener = new NexumListener(port, false, key);

            _listener.OnAccept += _listener_OnAccept;
            _listener.Listen();
        }
        public void Stop()
        {
            lock (_clients)
            {
                if (_stopped)
                    return;
                _stopped = true;

                _listener.Stop();

                IList<MirrorClient> clients = _clients.Values;
                for (int i = 0; i < clients.Count; i++)
                    clients[i].Close();
                _clients.Clear();
            }
        }

        internal void AddClient(MirrorClient client)
        {
            lock (_clients)
            {
                if (!_clients.ContainsKey(client.Id))
                    _clients.Add(client.Id, client);
            }
        }
        internal void RemoveClient(MirrorClient client)
        {
            lock (_clients)
            {
                if(_clients.ContainsKey(client.Id))
                    _clients.Remove(client.Id);
            }
        }

        private void _listener_OnAccept(Nexum n, NexumListener sender)
        {
            new MirrorClient(this, n);
        }
    }
}
